<?php
/**
 * @version		$Id: helper.php 21020 2011-03-27 06:52:01Z infograf768 $
 * @package		Joomla.Site
 * @subpackage	mod_stats
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// no direct access
defined('_JEXEC') or die;

/**
 * @package		Joomla.Site
 * @subpackage	mod_stats
 * @since		1.5
 */
class modLatestProductHelper
{
	static function &getList(&$params)
	{
		static $latestProductIds;
		
		$db = JFactory::getDbo();
		
		$query  = " SELECT DISTINCT a.id, a.*, IF(a.location = '*', 'all-location', i.name) AS location_name FROM #__je_products a";
		$query .= " JOIN #__je_product_info pi ON a.id = pi.product_id ";
		$query .= " LEFT JOIN #__je_info i ON ( i.id = a.location ) "; 
		$query .= " WHERE a.state = 1 ";
		
		$catid = $params->get('cat', 0);
		$featured = $params->get('featured', 0);
		
		if(!$catid)
			$catid = JRequest::getVar('catid', null);
		
		$loc = $params->get('loc', 0);
		
		if(!$loc)
			$loc = JRequest::getVar('loc', null);
		
		$limit = $params->get('count', 0);
			
		if($catid)
			$query .= " AND a.catid = '$catid' ";
			
		if($loc)
			$query .= " AND a.location = '$loc' ";
			
		if($featured)
			$query .= " AND a.sticky = 1 ";
			
		$nullDate 	= $db->quote($db->getNullDate());
        $nowDate 	= $db->quote(JFactory::getDate());
		
        if(!$featured)
        {
        	$query .= "	AND (a.publish_up = $nullDate OR a.publish_up <= $nowDate)
						AND (a.publish_down = $nullDate OR a.publish_down >= $nowDate) ";			
        }
			
		if(!empty($latestProductIds))
		{
			$query .= " AND a.id NOT IN (".implode(',', $latestProductIds).")";
		}
		
		$query .= " GROUP BY a.id ";
		
		$query .= " ORDER BY a.publish_up DESC ";
		
		if($limit)
			$query .= " LIMIT $limit ";
			
		//echo str_replace('#__', 'jos_', $query);
		
		$db->setQuery($query);
		$result = $db->loadObjectList();
		
		#echo mysql_error();
		
		if(!$featured)
		{
			foreach ($result as $item)
			{
				$latestProductIds[] = $item->id;
			}			
		}
			
		return $result;
	}
}